"use client";

import { useState } from "react";
import {
  Card,
  Avatar,
  Button,
  Modal,
  Form,
  Input,
  Radio,
  Upload,
  message,
} from "antd";
import {
  UserOutlined,
  EditOutlined,
  UploadOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import type { UploadProps } from "antd";
import { userControllerUpdateUser } from "@/app/servers/api/user";
import { fileUploadControllerUploadFile } from "@/app/servers/api/fileUpload";
import { useRouter } from "next/navigation";
import { userInfoAction } from "@/app/stores/userInfo.store";

export interface BasicInfoProps {
  userInfo: API.GetUserInfoDto;
}

export const BasicInfo: React.FC<BasicInfoProps> = ({
  userInfo: initalUserInfo,
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [isUploadingAvatar, setIsUploadingAvatar] = useState(false);
  const [form] = Form.useForm();
  const router = useRouter();

  // 从localStorage获取用户信息
  const [userInfo, setUserInfo] = useState<API.User>(initalUserInfo);

  // 获取头像URL的函数

  // 更新用户信息并保存到localStorage的函数
  const updateUserInfo = (newUser: API.User) => {
    setUserInfo(newUser);
    localStorage.setItem("userInfo", JSON.stringify(newUser));
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleAvatarUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    const formData = new FormData();
    formData.append("file", file);

    try {
      const response = await fileUploadControllerUploadFile({
        data: formData,
      });
      if (response.data) {
        const { data: newUser } = await userControllerUpdateUser({
          id: userInfo.id,
          avatarId: response.data.id,
        });
        updateUserInfo(newUser);
        onSuccess?.(response);
        message.success("头像更新成功");
        setIsUploadingAvatar(false);
        userInfoAction.updateAvatr(response.data);
      } else {
        onError?.(new Error("Upload failed"));
      }
    } catch (error) {
      onError?.(error as Error);
      message.error("头像更新失败");
    }
  };

  const uploadProps: UploadProps = {
    name: "file",
    accept: "image/*",
    showUploadList: false,
    beforeUpload: (file) => {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        message.error("只能上传图片文件！");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error("图片大小不能超过2MB！");
        return false;
      }
      return true;
    },
    customRequest: handleAvatarUpload,
  };

  const handleEdit = () => {
    form.setFieldsValue({
      username: userInfo.username,
      gender: userInfo.gender,
      bio: userInfo.bio,
    });
    setIsEditing(true);
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const { data: newUser } = await userControllerUpdateUser({
        id: userInfo.id,
        ...values,
      });
      updateUserInfo(newUser);
      setIsEditing(false);
      message.success("保存成功");
    } catch {
      message.error("保存失败");
    }
  };

  const handleLogout = () => {
    // 清除用户信息
    localStorage.removeItem("userInfo");
    // 清除其他可能的登录状态
    localStorage.removeItem("token");
    // 跳转到登录页
    router.push("/customer/login");
  };

  return (
    <div>
      <Card className="shadow-lg rounded-lg">
        <div className="flex justify-between items-start">
          <div className="flex items-start space-x-8">
            <div
              className="relative group cursor-pointer"
              onClick={() => setIsUploadingAvatar(true)}
            >
              <Avatar
                size={120}
                icon={<UserOutlined />}
                src={userInfo?.avatarFile?.href}
                className="border-4 border-white shadow-lg rounded-full"
              />
              <div className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-40 opacity-0 group-hover:opacity-100 transition-opacity rounded-full">
                <PlusOutlined className="text-white text-xl" />
              </div>
            </div>
            <div className="space-y-4">
              <div>
                <h2 className="text-2xl font-bold text-gray-800">
                  {userInfo.username}
                </h2>
                <p className="text-gray-500 italic">
                  {userInfo.bio || "这个人很懒，还没有签名~"}
                </p>
              </div>
              <div className="space-y-3">
                <p className="text-gray-600">
                  <span className="font-medium text-gray-800">ID：</span>
                  {userInfo.id}
                </p>
                <p className="text-gray-600">
                  <span className="font-medium text-gray-800">性别：</span>
                  {userInfo.gender === "male"
                    ? "男"
                    : userInfo.gender === "female"
                    ? "女"
                    : "其他"}
                </p>
                <p className="text-gray-600">
                  <span className="font-medium text-gray-800">邮箱：</span>
                  {userInfo.email}
                </p>
                <p className="text-gray-600">
                  <span className="font-medium text-gray-800">创建时间：</span>
                  {userInfo.createdAt}
                </p>
              </div>
            </div>
          </div>
          <div className="space-y-2">
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={handleEdit}
              className="bg-blue-500 hover:bg-blue-600 w-full"
            >
              编辑资料
            </Button>
            <Button danger onClick={handleLogout} className="w-full">
              退出登录
            </Button>
          </div>
        </div>
      </Card>

      <Modal
        title="编辑个人资料"
        open={isEditing}
        onOk={handleSave}
        onCancel={() => setIsEditing(false)}
        className="top-8"
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={userInfo}
          className="mt-4"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input maxLength={20} placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item name="gender" label="性别">
            <Radio.Group>
              <Radio value="male">男</Radio>
              <Radio value="female">女</Radio>
              <Radio value="other">其他</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item name="bio" label="个性签名">
            <Input.TextArea
              maxLength={100}
              placeholder="写点什么来介绍自己吧..."
              autoSize={{ minRows: 2, maxRows: 4 }}
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="更换头像"
        open={isUploadingAvatar}
        onCancel={() => setIsUploadingAvatar(false)}
        footer={null}
        width={400}
      >
        <div className="flex flex-col items-center py-6">
          <Avatar
            size={120}
            icon={<UserOutlined />}
            src={userInfo.avatarFile?.href}
            className="mb-6 border-2 border-gray-200"
          />
          <Upload {...uploadProps}>
            <Button icon={<UploadOutlined />}>选择图片</Button>
          </Upload>
          <p className="text-gray-400 text-sm mt-4">
            支持 jpg、png 格式，文件小于 2MB
          </p>
        </div>
      </Modal>
    </div>
  );
};
export default BasicInfo;
